package com.base.data.tools;


import androidx.annotation.NonNull;

import com.base.common.app.BaseConstant;
import com.base.common.utils.DateUtils;
import com.base.common.utils.IOUtils;
import com.base.common.utils.ThreadManager;
import com.base.data.annotations.TableField;
import com.base.data.common.Config;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import static com.base.common.app.BaseConstant.GS;
import static com.base.common.app.BaseConstant.RS;
import static com.base.common.app.BaseConstant.US;


public class LogUtils implements Config {

    public static String data_log;//当前日期，
    public static String fileName;//文件名

    private LogUtils() {
    }


    public static void checkFileName() {
        String now = DateUtils.getNowDateString_simple();
        if (!now.equals(data_log)) {
            data_log = DateUtils.getNowDateString_simple();
            fileName = data_log + ".txt";
            //检查是否存在文件,没有则创建
            IOUtils.createFile(BaseConstant.logSaveDir, fileName);
        }
    }


    /**
     * @param username  用户名
     * @param operation 什么操作
     * @param result    结果
     */

    public static void select_write(String username, String operation, String tabName, String result) {
        write(DateUtils.getNowDateString(), username, operation, tabName, result, "", "");
    }


    /**
     * @param updateBeforeBean 修改之前的，
     * @param updateBean       修改的数据
     * @param isSucceed        是否修改成功
     * @param <T>
     */
    public static <T> void update_write(@NonNull final T updateBeforeBean, @NonNull final T updateBean, @NonNull final String userName, final boolean isSucceed) {
        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {
                Class<?> type = updateBean.getClass();

                String time = DateUtils.getNowDateString();
                String operation = "update";
                String tabName = SqliteUtils.toTabNameDefault(type);
                String res_des = isSucceed ? "success" : "unSuccess";

                StringBuffer update_before = new StringBuffer();
                StringBuffer update = new StringBuffer();

                try {
                    for (Field field : type.getDeclaredFields()) {

                        if (field.isAnnotationPresent(TableField.class)) {
                            TableField tableFieldInfo = field.getAnnotation(TableField.class);
                            if (!tableFieldInfo.exist()) continue;
                        }
                        field.setAccessible(true);
                        //如果属性的值不为空则为需更新的数据
                        Object upda = field.get(updateBean);
                        if (upda != null) {
                            Object before = field.get(updateBeforeBean);
                            if (before == null) before = "";

                            update_before.append(field.getName());
                            update_before.append("=");
                            update_before.append(before.toString());
                            update_before.append(US);


                            update.append(field.getName());
                            update.append("=");
                            update.append(upda.toString());
                            update.append(US);

                        }
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (update_before.length() > 0)
                    update_before.deleteCharAt(update_before.length() - 1);
                if (update.length() > 0) update.deleteCharAt(update.length() - 1);

                write(time, userName, operation, tabName, res_des, update_before.toString(), update.toString());
            }
        });

    }


    public static void updata_delete_write(@NonNull final Class clas, @NonNull final String userName, @NonNull final String key, @NonNull final String keyValues, final boolean isSucceed) {
        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {
                String res_des = isSucceed ? "success" : "unSuccess";
                String operation = "update";
                String time = DateUtils.getNowDateString();
                String tabName = SqliteUtils.toTabNameDefault(clas);
                write(time, userName, operation, tabName, res_des, key + "=" + keyValues + US + "is_del=1", key + "=" + keyValues + US + "is_del=2");
            }
        });
    }

    /**
     * @param deleteBean 删除的数据
     * @param isSucceed  是否修改成功
     * @param <T>
     */
    public static <T> void delete_write(@NonNull final T deleteBean, @NonNull final String userName, final boolean isSucceed) {
        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {
                Class<?> type = deleteBean.getClass();

                String time = DateUtils.getNowDateString();
                String operation = "deleteById";
                String tabName = SqliteUtils.toTabNameDefault(type);
                String res_des = isSucceed ? "success" : "unSuccess";

                StringBuffer delete = new StringBuffer();

                try {
                    for (Field field : type.getDeclaredFields()) {
                        field.setAccessible(true);
                        //如果属性的值不为空则为需更新的数据
                        Object dele = field.get(deleteBean);
                        if (dele != null) {
                            delete.append(field.getName());
                            delete.append("=");
                            delete.append(dele.toString());
                            delete.append(US);
                        }
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (delete.length() > 0) delete.deleteCharAt(delete.length() - 1);

                write(time, userName, operation, tabName, res_des, "", delete.toString());
            }
        });

    }

    /**
     * 插入成功的数据会有id  失败的则没有id
     *
     * @param insertBean
     * @param userName
     * @param isSucceed
     * @param <T>
     */
    public static <T> void insert_write(@NonNull final T insertBean, @NonNull final String userName, final boolean isSucceed) {
        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {
                Class<?> type = insertBean.getClass();

                String time = DateUtils.getNowDateString();
                String operation = "insert";
                String tabName = SqliteUtils.toTabNameDefault(type);
                String res_des = isSucceed ? "success" : "unSuccess";

                StringBuffer insert = new StringBuffer();

                try {
                    for (Field field : type.getDeclaredFields()) {
                        field.setAccessible(true);
                        //如果属性的值不为空则为需更新的数据
                        Object inser = field.get(insertBean);
                        if (inser != null) {
                            insert.append(field.getName());
                            insert.append("=");
                            insert.append(inser.toString());
                            insert.append(US);
                        }
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (insert.length() > 0) insert.deleteCharAt(insert.length() - 1);

                write(time, userName, operation, tabName, res_des, "", insert.toString());
            }
        });

    }


    /**
     * 时间    用户    操作     表名    结果描述  执行前的数据   执行的数据
     *
     * @param time            时间
     * @param user            用户
     * @param operation       操作
     * @param tabName         表名
     * @param res_des         结果描述
     * @param ope_before_data 执行前的数据
     * @param ope_date        执行的数据
     */
    public static void write(String time, String user, String operation, String tabName, String res_des, String ope_before_data, String ope_date) {
        StringBuffer sb = new StringBuffer();
        sb.append(time);
        sb.append(RS);
        sb.append(user);
        sb.append(RS);
        sb.append(operation);
        sb.append(RS);
        sb.append(tabName);
        sb.append(RS);
        sb.append(res_des);
        sb.append(RS);
        sb.append(ope_before_data);
        sb.append(RS);
        sb.append(ope_date);
        sb.append(GS);

        //检查写入的文件
        checkFileName();
        IOUtils.writeFile_row(BaseConstant.logSaveDir, fileName, sb.toString());
    }

    /**
     * String[] str
     * str[0]    str[1]
     * * 时间    用户    操作     表名    结果描述  执行前的数据   执行的数据
     * *
     * * @param time            时间
     * * @param user            用户
     * * @param operation       操作
     * * @param tabName         表名
     * * @param res_des         结果描述
     * * @param ope_before_data 执行前的数据
     * * @param ope_date        执行的数据
     *
     * @param filePath
     * @return
     */
    public static List<String[]> read(@NonNull String filePath) {
        List<String> list = IOUtils.readTxtFile(filePath);

        List<String[]> listsss = new ArrayList<>();
        for (String s : list) {
            String[] str = s.split(String.valueOf(RS));
            listsss.add(str);
        }
        return listsss;
    }


}
